package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.autoconfig.template.MinIOTemplate;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {


    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOTemplate minIOTemplate;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    //生成静态文件上传到minIO中
    @SneakyThrows
    @Override
    public void buildArticleToMinIO(Long articleId, String content) {
        //1. 封装用来生成静态页的   模型数据
        List<Map> params = JSONArray.parseArray(content, Map.class);
        Map map = new HashMap();
        map.put("content", params);

        //2. 根据 模板 和 数模型数据   生成静态页数据
        Template template = configuration.getTemplate("article.ftl");
        StringWriter out = new StringWriter();
        template.process(map, out);

        //3. 把静态页面数据上传到MinIO中
        InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
        String url = minIOTemplate.uploadHtmlFile(
                "", articleId + ".html", inputStream);

        //4. 修改数据库中文章数据，回写静态页面的url地址
        ApArticle article = new ApArticle();
        article.setId(articleId);
        article.setStaticUrl(url);
        apArticleMapper.updateById(article);

        //发送消息，进行ES索引库的数据同步
        addArticle2EsIndex(articleId, content);
    }

    private void addArticle2EsIndex(Long articleId, String content) {
        //1. 根据文章id查询文章数据
        ApArticle article = apArticleMapper.selectById(articleId);

        //2.  封装 需要传递的对象数据
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article, vo);
        vo.setContent(content);

        //3. 发送消息  第一次测试的时候，可能消息发送失败，第一次失败的原因是topic没有创建
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));

        System.out.println("文章静态页生成后，同步ES的消息发送成!");
    }
}